package cn.itsource.pethome.system.atools.fast;

import cn.itsource.pethome.utils.AjaxResult;
import cn.itsource.pethome.utils.FastdfsUtil;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Author:R
 * @Date:2023/1/7 19:50
 * @Description 上传（删除）文件到fastDFS文件服务器
 */
@RestController
@RequestMapping("/fast")
@Api(value = "文件上传到fastDFS服务器的API",description = "文件上传到fastDFS服务器")
public class FastController {
    //上传
    /**
     * @RequestPart 请求参数认证  required = true 必传   value = "file" 前端请求的参数名叫file
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){
        try {
            byte[] bytes = file.getBytes();
            //获取上传的文件名
            String filename = file.getOriginalFilename();
            //获取后缀
            String suffix = filename.substring(filename.lastIndexOf(".") + 1);
            String path = FastdfsUtil.upload(bytes, suffix);
            return AjaxResult.success().setData(path);//上传成功，返回路径
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常，请联系管理员");
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常，请联系管理员");
        }
    }

    //删除
    @DeleteMapping
    public AjaxResult delete(@RequestParam(required = true,value = "path") String  path){
        try {
            //前端传递过来的文件形式:/group1/M00/03/68/CgAIC2O5LmiAJXbsAAI3GK6t8KE523.jpg
            String filePath = path.substring(1);   // group1/M00/03/68/CgAIC2O5LmiAJXbsAAI3GK6t8KE523.jpg
            String groupName = filePath.substring(0, filePath.indexOf("/"));//group1
            String finleName = filePath.substring(filePath.indexOf("/") + 1);//M00/03/68/CgAIC2O5LmiAJXbsAAI3GK6t8KE523.jpg
            FastdfsUtil.delete(groupName,finleName);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常，请联系管理员");
        }
    }
}
